<template>
  <div class="home">
    <my-header>手机号登录</my-header>
    <div class="form">
      <div>
        手机号：<input type="text" v-model="mobile" placeholder="请输入手机号码">
      </div>
      <div>
        验证码：<input type="text" v-model="code" placeholder="请输入验证码"><button @click="getCode">{{text}}</button>
      </div>
    </div>
    <button class="login-btn" :disabled="disabled" @click="login">登录</button>
  </div>
</template>

<script>
import myHeader from '@/components/myHeader/myHeader'
// 手机号验证正则
let regMobile = /^1[356789]\d{9}/
// 验证码正则
let redCode = /^\d{4,6}$/
let timer
export default {
  name: 'Home',
  components: {
    myHeader,
  },
  data() {
    return {
      mobile: '',
      code: '',
      text: '发送验证码',
      disabled: true,
      isSend: false // 定义是否发送了验证码
    }
  },
  created() {
  },

  methods: {
    getCode() {
      if(!this.mobile) {
       this.load('请输入手机号')
      } else if(!regMobile.test(this.mobile)) {
        this.load('手机号码格式不正确')
      } else {
        this.load('发送成功')
        this.isSend = true
        let num = 60
        timer = setInterval(() => {
          if(num > 0) {
            num--
            this.text = '倒计时' + num + '秒'
          } else {
            clearInterval(timer)
            this.text = '获取验证码'
            this.isSend = false
          }
        }, 1000);
      }
    },
    load(msg) {
      this.$loading.show(msg)
      setTimeout(() => {
        this.$loading.hide()
      }, 1000);
    },


    login() {
      if(!this.isSend) {
        this.load('请先获取验证码')
      } else if(!redCode.test(this.code)) {
        this.load('验证码格式不正确')
      } else {
        this.$router.push('/dreams')
      }
    }
  },


  watch: {
    mobile(to, from) {
      if(regMobile.test(to) && redCode.test(this.code)) {
        this.disabled = false
      } else {
        this.disabled = true
      }
    },

    code(to, from) {
      if(regMobile.test(this.mobile) && to) {
        this.disabled = false
      } else {
        this.disabled = true
      }
    }
  }
}
</script>
<style scoped>
  .form {
    width: 80%;
    margin: 0 auto;
    margin-top: 200px;
  }
  .form div{
    width: 100%;
  }
  .form div input {
    width: 120px;
    line-height: 26px;
    border-radius: 0;
  }
  button {
    margin-left: 20px;
  }
  .login-btn {
  width: 90px;
  display: block;
  line-height: 30px;
  margin: 20px auto;
  background-color: yellowgreen;
  border: none;
  border-radius: 8px;
  outline: none;}
  .login-btn[disabled] {
  background-color: #ccc;}
</style>
